import React, { useState, useEffect, useRef } from 'react';  // 添加 useEffect 导入
import * as SpiceHtml5 from '@spice-project/spice-html5/src/main';

// 定义组件的属性类型
interface SpiceClientProps {
  url: string;
  className?: string;
  style?: React.CSSProperties;
}

// 创建 SpiceClient 组件
const SpiceClientModal: React.FC<SpiceClientProps> = ({ url, className, style }) => {
  const DEBUG = false;
  const [spiceConn, setSpiceConn] = useState(null);
  const screenRef = useRef<HTMLDivElement>(null); // 新增 DOM 引用
  
  const spice_error = (e: unknown) => {
    if (spiceConn != null) {
      (spiceConn as { stop: () => void }).stop();
    }
  };

  const agent_connected = (e: unknown) => {
    SpiceHtml5.resize_helper(this);
    console.log('Agent connected:', e);
  };


  // 调整 useEffect 位置并添加清理函数
  useEffect(() => {


    try {
      if (DEBUG) {
        const conn = new SpiceHtml5.SpiceMainConn(
          {
            uri: url,
            screen_id: "spice-screen",
            dump_id: "debug-div",
            message_id: "message-div",
            password: '',
            onerror: spice_error,
            onagent: agent_connected
          });
        setSpiceConn(conn);
      } else {
        const conn = new SpiceHtml5.SpiceMainConn({
          uri: url, 
          screen_id: "spice-screen",
          password: '', 
          onerror: spice_error, 
          onagent: agent_connected
        });
        conn.log_err = ()=>{};
        conn.log_warn = ()=>{};
        conn.log_info = ()=>{};
        setSpiceConn(conn);
      }
    } catch (e) {
      console.error('Error creating Spice connection:', e);
    }

    // 添加清理函数
    return () => {
      if (spiceConn) {
        (spiceConn as { stop: () => void }).stop();
        setSpiceConn(null);
      }
    };
  }, [ url ]);

  return (
    <div>
      <div id="login">
        <span className="logo">SPICE</span>
      </div>

      <div id="spice-area">
        <div id="spice-screen" className="spice-screen" ref={screenRef}></div>
      </div>
      {DEBUG && <>
        <div id="message-div" className="spice-message"></div>
        <div id="debug-div">
        </div>
          </>
      }
 
      

    </div>
  );
};

export default SpiceClientModal;